import com.sun.source.tree.Tree;

import java.time.temporal.Temporal;
import java.util.*;

public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    /**
     * 手动创建二叉树，创建完成之后，返回根节点
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }

    /**
     * 获取树中节点的个数
     */
    public int nodeSize = 0;
    public void size(TreeNode root) {
        if(root == null) {
            return;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    public int size2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return size2(root.left) + size2(root.right) + 1;
    }

    /**
     * 获取叶子节点的个数
     */
    public int leafSize = 0;
    public void getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    public int getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    /**
     * 获取第 K 层节点的个数
     */
    public int getKLevelNodeCount(TreeNode root, int k) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1) + getKLevelNodeCount(root.right,k-1);
    }

    /**
     * 获取二叉树的高度 时间复杂度 O(N) 空间复杂度 O（logN）
     */
    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.max(leftHeight, rightHeight) + 1;
    }

    public int getHeight2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        //int leftHeight = getHeight2(root.left);
        //int rightHeight = getHeight2(root.right);

        //return leftHeight > rightHeight ? leftHeight+1 : rightHeight+1;
        return getHeight2(root.left) > getHeight2(root.right) ? getHeight2(root.left)+1: getHeight2(root.right)+1;
    }

    public int getHeight3(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        int rightHeight = getHeight(root.right);
        if(rightHeight < 0) {
            return -1;
        }
        if(/*leftHeight >=0 && rightHeight >= 0*/Math.abs(leftHeight-rightHeight) <= 1) {
            return Math.max(leftHeight,rightHeight)+1;
        }else {
            return -1;
        }
    }

    /**
     * 检测值为 value 的元素是否存在
     */
    public TreeNode find(TreeNode root, int val) {
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode ret = find(root.left,val);
        if(ret != null) {
            //左树找到了；
            return ret;
        }
        ret = find(root.right,val);
        if(ret != null) {
            //右数找到了
            return ret;
        }
        return null;
    }

    /**
     * 层序遍历
     */
    public void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.println(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            //每一层的 list
            List<Character> list = new ArrayList<>();
            //通过这个 size 确定一层有多少个元素
            int size = queue.size();//1
            while(size != 0) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }

    /**
     * 判断一棵树是不是完全二叉树
     */
    public boolean isCompleteTree(TreeNode root) {
        if(root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur == null) {
                break;
            }
            queue.offer(cur.left);
            queue.offer(cur.right);
        }

        while(!queue.isEmpty()) {
            TreeNode top = queue.peek();
            if(top != null) {
                return false;
            }
            queue.poll();
        }
        return true;
    }

    /**
     * 判断两棵树是否相同
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) {
            return true;
        }else if(p == null || q == null) {
            return false;
        }else if(p.val != q.val) {
            return false;
        }else {
            return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        }
    }

    /**
     * 另一颗树的子树
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) {
            return true;
        }
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        if(isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }

    /**
     * 翻转二叉树
     */
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public TreeNode invertTree2(TreeNode root) {
        if(root == null) {
            return null;
        }
        TreeNode leftT = invertTree2(root.left);
        TreeNode righT = invertTree2(root.right);
        if(leftT == null && righT == null) {
            return root;
        }
        root.left = righT;
        root.right = leftT;
        return root;
    }

    /**
     * 平衡二叉树  平衡二叉树 是指该树所有节点的左右子树的高度相差不超过 1。
     */
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int lH = getHeight(root.left);
        int rH = getHeight(root.right);

        return Math.abs(lH-rH)<=1 && isBalanced(root.left) && isBalanced(root.right);
    }

    public boolean isBalanced2(TreeNode root) {
        if(height(root) < 0) {
            return false;
        }
        return true;
    }

    public int height(TreeNode root) {
        if(root == null) {
            return 0;
        }

        int lh = height(root.left);
        if(lh < 0) {
            return -1;
        }

        int rh = height(root.right);
        if(rh < 0) {
            return -1;
        }

        if(Math.abs(lh - rh) <= 1) {
            return Math.max(lh,rh)+1;
        }else {
            return -1;
        }
    }

    /**
     * 对称二叉树
     */
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left, root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if(leftTree == null && rightTree != null || leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree == null && rightTree == null) {
            return true;
        }
        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right) && isSymmetricChild(leftTree.right,rightTree.left);
    }

    public boolean isSymmetric2(TreeNode root) {
        return check(root,root);
    }

    public boolean check(TreeNode u, TreeNode v) {
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(u);
        q.offer(v);
        while(!q.isEmpty()) {
            u = q.poll();
            v = q.poll();
            if(u == null && v == null) {
                continue;//跳过后序步骤，说明此分支对称
            }
            if((u == null || v == null) || (u.val != v.val)) {
                return false;
            }

            q.offer(u.left);
            q.offer(v.right);

            q.offer(u.right);
            q.offer(v.left);
        }
        return true;
    }

    /**
     * 根据二叉树的前序遍历结果创建二叉树
     */
    public static int i = 0;
    public static TreeNode  createTree1(String str) {
        TreeNode root = null;
        if(str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree1(str);
            root.right = createTree1(str);
        }else {
            i++;
        }
        return root;
    }

    /**
     * 二叉树进行中序遍历
     */
    public static void inOderTraversal(TreeNode root) {
        if(root == null) {
            return;
        }
        inOderTraversal(root.left);
        System.out.println(root.val);
        inOderTraversal(root.right);
    }

    /**
     * 二叉树的层序遍历
     */
    public List<List<Character>> levelOrer(TreeNode root) {
        List<List<Character>> ret = new ArrayList<List<Character>>();
        if(root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            List<Character> level = new ArrayList<Character>();
            int currentLevelSize = queue.size();
            for (int i = 0; i <= currentLevelSize; i++) {
                TreeNode cur = queue.poll();
                level.add(cur.val);

                if(cur.left != null) {
                    queue.offer(cur.left);
                }

                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }

    /**
     * 二叉树的最近公共祖先
     */
    //先找到 祖先节点左边的目标 1节点，找到左边这个节点后，做了标记，后序再找此目标 1节点的兄弟节点，如果此节点是目标而节点，就做后续判断，根据 leftV 与 rightV 都不为空，就可只其结果就是他们的祖先节点
    //如果在左边找不到， 就到 祖先节点 的右边找，后续就是和上一行一样的结果
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }

        if(root == p || root == q) {
            return root;
        }


        TreeNode leftV = lowestCommonAncestor(root.left,p,q);
        TreeNode rightV = lowestCommonAncestor(root.right,p,q);

        if(leftV != null && rightV != null) {
            return root;
        }

        if(leftV != null) {
            return leftV;
        }

        if(rightV != null) {
            return rightV;
        }

        return null;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }

        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();

        getPath(root,p,stackP);

        getPath(root,q,stackQ);

        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        int size = sizeP - sizeQ;

        if(size < 0) {
            //第2个栈中元素多
            size = sizeQ - sizeP;
            //第2个栈 出size个元素
            while(size != 0) {
                stackQ.pop();
                size--;
            }

        }else {
            //第1个栈中元素多
            while(size != 0) {
                stackP.pop();
                size--;
            }
        }

        //代码走到这里 说明 2个栈当中 元素的个数是一样的了
        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            if(stackP.peek() == stackQ.peek()) {
                return stackP.peek();
            }else {
                stackP.pop();
                stackQ.pop();
            }
        }
        return null;
    }

    private boolean getPath(TreeNode root, TreeNode node, Stack stack) {
        if(root == null || node == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flg = getPath(root.left,node,stack);
        if(flg) {
            return true;
        }
        boolean flg2 = getPath(root.right,node,stack);
        if(flg2) {
            return true;
        }
        stack.pop();
        return false;
    }



}
